import { _decorator, find, Node } from 'cc';
import { BaseLayer } from './BaseLayer';
import { SdkMgr } from '../manager/SdkMgr';
import { EffMgr } from '../manager/EffMgr';
import { Ins } from '../Ins';
import { ENUM_UI_LAYER } from '../Enum';
import { ReqMgr } from '../manager/ReqMgr';
import { DataMgr } from '../manager/DataMgr';
const { ccclass, property } = _decorator;

@ccclass('AuthLayer')
export class AuthLayer extends BaseLayer {
    auth_ready: Node = null
    auth_run: Node = null

    onLoad() {
        this.auth_ready = find('panel/main/buttons/auth_ready', this.node)
        this.auth_run = find('panel/main/buttons/auth_run', this.node)
    }

    onEnable() {
        this.auth_ready.active = true
        this.auth_run.active = false
        SdkMgr.ins.getLoginInfo((info: any) => {
            if (info.status) {
                this.auth_ready.active = false
                this.auth_run.active = true
                SdkMgr.ins.getLoginCode(async (obj: any) => {
                    const data: any = await ReqMgr.ins.request('login', 'get', { code: obj.data })
                    if (!data.status) {
                        EffMgr.ins.showTip('EffTip', '服务器异常')
                        Ins.UIMgr.toggle(ENUM_UI_LAYER.AUTH, false)
                        Ins.UIMgr.toggle(ENUM_UI_LAYER.MENU)
                        return
                    }
                    // 缓存数据
                    DataMgr.ins.user = info.data
                    DataMgr.ins.user.openid = data.openid
                    DataMgr.ins.save()
                    // 进排行榜
                    Ins.UIMgr.toggle(ENUM_UI_LAYER.AUTH, false)
                    Ins.UIMgr.toggle(ENUM_UI_LAYER.RANK)
                })
            } else {
                EffMgr.ins.showTip('EffTip', '您拒绝了授权')
                Ins.UIMgr.toggle(ENUM_UI_LAYER.AUTH, false)
                Ins.UIMgr.toggle(ENUM_UI_LAYER.MENU)
            }
        })
    }
}


